package com.mjk.common.tools.encrypt;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.digest.SM3;
import com.alibaba.fastjson.JSONObject;
import com.mjk.common.tools.logger.BizLogger;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * 国密3Demo
 * <p>
 * TODO:
 * 需要的类库，maven管理，或者下载到例如lib目录，右键添加为库
 * com.alibaba/fastjson 1.2.83 https://mvnrepository.com/artifact/com.alibaba/fastjson/1.2.83
 * cn.hutool/hutool-core 5.8.6 https://mvnrepository.com/artifact/cn.hutool/hutool-core/5.8.6
 * cn.hutool/hutool-crypto 5.8.6 https://mvnrepository.com/artifact/cn.hutool/hutool-crypto/5.8.6
 * org.bouncycastle/bcprov-jdk15on 1.6.9 https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on/1.69
 *
 * @author oyzh
 * @since 2022/9/16
 */
public class SM3Utils {
    private static final String ENCODING = "UTF-8";

    /**
     * 验签
     *
     * @param plainText 待签串
     * @param sign      签名
     * @return 结果
     */
    public static boolean verify(String plainText, String sign) {
        return sign(plainText).equals(sign);
    }

    /**
     * @param plainText 待签串
     * @return 签名
     */
    public static String sign(String plainText) {
        try {
            SM3 sm3 = SmUtil.sm3();
            byte[] digest = sm3.digest(plainText.getBytes(StandardCharsets.UTF_8));
            return java.util.Base64.getUrlEncoder().encodeToString(digest);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 通过密钥进行加密
     * @explain 指定密钥进行加密
     * @param key
     *            密钥
     * @param data
     *            被加密的byte数组
     * @return
     */
    public static String hmac(String key, String data) {
        try {
            byte[] srckey = key.getBytes(ENCODING);
            byte[] srcData = data.getBytes(ENCODING);
            KeyParameter keyParameter = new KeyParameter(srckey);
            SM3Digest digest = new SM3Digest();
            HMac mac = new HMac(digest);
            mac.init(keyParameter);
            mac.update(srcData, 0, srcData.length);
            byte[] result = new byte[mac.getMacSize()];
            mac.doFinal(result, 0);
            return ByteUtils.toHexString(result);
        }catch(Exception e){
            BizLogger.error(e);
        }
        return "";
    }
    public static void main(String[] args) {
        SM3Utils sm3Demo = new SM3Utils();
    }
}

